package com.blue.Impl.workflow;

import com.blue.common.constant.CommonConstant;
import com.blue.vo.workflow.TaskInstanceVO;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.blue.mapper.workflow.TaskInstanceMapper;
import com.blue.po.workflow.TaskInstancePO;
import com.blue.service.workflow.ITaskInstanceService;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Service
public class TaskInstanceServiceImpl extends ServiceImpl<TaskInstanceMapper, TaskInstancePO> implements ITaskInstanceService {

    @Override
    public void computeTime(String status, List<TaskInstancePO> taskInstancePOS) {
        if (CollectionUtils.isEmpty(taskInstancePOS)) {
            return;
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //待处理的需要计算距离当前已滞留时长
        if (CommonConstant.PENDING.equals(status)) {
            LocalDateTime end = LocalDateTime.now();
            taskInstancePOS.forEach(item -> {
                String createTime = item.getCreateTime();
                LocalDateTime start = LocalDateTime.parse(createTime, dateTimeFormatter);
                Duration duration = Duration.between(start, end);
                long hours = duration.toHours();//相差的小时数
                long minutes = duration.toMinutes() % 60;//相差的分钟数
                item.setRetentionTime((hours == 0 ? "" : hours + "小时") + minutes + "分钟");
            });
            //非待处理计算节点耗时
        } else {
            taskInstancePOS.forEach(item -> {
                LocalDateTime start = LocalDateTime.parse(item.getCreateTime(), dateTimeFormatter);
                LocalDateTime end = LocalDateTime.parse(item.getOperationTime(), dateTimeFormatter);
                Duration duration = Duration.between(start, end);
                long hours = duration.toHours();//相差的小时数
                long minutes = duration.toMinutes() % 60;//相差的分钟数
                item.setRetentionTime((hours == 0 ? "" : hours + "小时") + minutes + "分钟");
            });
        }
    }

    @Override
    public List<TaskInstanceVO> taskNodeList(String instanceId) {
        return baseMapper.taskNodeList(instanceId);
    }
}
